import Proj, { InterfaceProjection } from "proj4";

export interface FourParams {
  x_0: number; // east false
  y_0: number; // north false
  t: number; // rotation
  k: number; // scale
}

export class ProjHelper_BJ54 {
  private localProj: InterfaceProjection;
  private beijing54Proj: InterfaceProjection;
  constructor() {
    // beijing54
    Proj.defs("EPSG:4214", "+proj=longlat +ellps=krass +no_defs");

    // proj 40 zone
    Proj.defs(
      "EPSG:2416",
      "+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=krass +units=m +no_defs"
    );

    // this.localProj = Proj.Proj("EPSG:42141");
    // this.beijing54Proj = Proj.Proj("EPSG:42140");
  }

  /**
   * cocal cartography's coordinates to beijing 54's projection coordinates
   * @param coord source coordinates
   * @param params four parameters
   */
  public localproj_bjproj(coord: [number, number], params: FourParams) {
    if (!coord) throw new Error("coordinate error!");
    const lon = coord[0];
    const lat = coord[1];

    const x_0 = params.x_0;
    const y_0 = params.y_0;
    const t = params.t;
    const k = params.k;

    let lon2, lat2;
    lon2 = x_0 + lon * k * Math.cos(t) - lat * k * Math.sin(t);
    lat2 = y_0 + lat * k * Math.cos(t) + lon * k * Math.sin(t);
    return [lon2, lat2];
  }

  /**
   *  beijing54's projection coordinates to beijing54's geographic coordinates
   *  ensure set projection before transform
   * @param coord
   */
  public bjproj_bjlnglat(coord: [number, number]) {
    let resCoord =  Proj.transform(
      Proj.Proj("EPSG:2416"),
      Proj.Proj("EPSG:4214"),
      coord.reverse()
    );

    return resCoord;
  }

  public bjlnglat_wgslnglat(coord: [number, number]) {
    return Proj.transform(
      Proj.Proj("EPSG:4214"),
      Proj.Proj("EPSG:4326"),
      coord
    );
  }

  public test(coord: [number, number]) {
    return Proj.transform(
      Proj.Proj("EPSG:4214"),
      Proj.Proj("EPSG:2416"),
      coord
    );
  }
}
